package org.demo.multisource.service;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.demo.multisource.entity.Teacher;
import org.demo.multisource.mapper.TeacherMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;

public interface TeacherService extends IService<Teacher> {

    void cusAdd();

    @Service("teacherService")
    class Default extends ServiceImpl<TeacherMapper,Teacher> implements TeacherService {

        @Autowired@Lazy
        private TeacherService thix;
        @Autowired
        private TeacherMapper mapper;

        @Override
        public void cusAdd() {
            Teacher teacher = new Teacher();
            teacher.setName("cus_add");
            teacher.setCreatetime(LocalDateTime.now());
            mapper.cusAdd(teacher);
            Teacher newTeacher = getBaseMapper().selectOne(new LambdaQueryWrapper<Teacher>().eq(Teacher::getId,teacher.getId()));
            // @DS注解目前只放在Mapper接口上，Service上没有
            // 批处理方法调用的时候，要手动设置数据源才行
            DynamicDataSourceContextHolder.push("db1");
            thix.saveOrUpdateBatch(Collections.singletonList(newTeacher));
        }
    }
}
